package com.gs.djys.checkfragments.opinion;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.gs.djys.Base.AddBean;
import com.gs.djys.Base.DictationResult;
import com.gs.djys.R;
import com.gs.djys.Util.NoScroolGridView;
import com.gs.djys.Util.ToastUtils;
import com.gs.djys.Util.Utils;
import com.gs.djys.mvp.MVPBaseFragment;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.lxj.matisse.Matisse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

import static android.app.Activity.RESULT_OK;

/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class OpinionFragment extends MVPBaseFragment<OpinionContract.View, OpinionPresenter> implements OpinionContract.View, RadioGroup.OnCheckedChangeListener {


    @Bind(R.id.rb_Male)
    RadioButton rbMale;
    @Bind(R.id.rb_FeMale)
    RadioButton rbFeMale;
    @Bind(R.id.rg_sex)
    RadioGroup rgSex;
    @Bind(R.id.sljg_lay)
    LinearLayout sljgLay;
    @Bind(R.id.sfz_list)
    NoScroolGridView sfzList;
    @Bind(R.id.zkms_et)
    EditText zkmsEt;
    @Bind(R.id.INQuality2)
    RelativeLayout INQuality2;
    @Bind(R.id.add_te)
    TextView addTe;
    @Bind(R.id.disease_new_parent_layout)
    RelativeLayout diseaseNewParentLayout;
    @Bind(R.id.disease_new_parent_layout2)
    LinearLayout diseaseNewParentLayout2;
    private String isty = "true";
    private static String APPID = "5bf211f5";
    private String dictationResultStr;
    private List<String> xf = new ArrayList<>();
    private List<String> zong = new ArrayList<>();
    private OpinionGridAdapter opinionGridAdapter;
    private Map<Integer, OpinionGridAdapter> mapAdapter = new HashMap<>();
    private int childViewPosition;//点击拍照获取的childveiw下标
    private List<String> PicDatas = new ArrayList<>();
    public void setChildViewPosition(int childViewPosition) {
        this.childViewPosition = childViewPosition;
    }

    @Override
    public void onRequestError(String msg) {
        ToastUtils.showShortToast(msg);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fra_opinion, container, false);
        ButterKnife.bind(this, view);
        rgSex.setOnCheckedChangeListener(this);
        initview();
        return view;
    }

    private void initview() {
        addTe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String pic = "";
                for (int i = 0; i < PicDatas.size(); i++) {
                    if (PicDatas.size() == 1) {
                        pic = PicDatas.get(i);
                    } else {
                        pic += PicDatas.get(i) + ",";
                    }
                }
                mPresenter.addData(isty, zkmsEt.getText().toString(), getActivity(),pic);
            }
        });
        INQuality2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getkdxf(zkmsEt);
            }
        });
        ArrayList<Drawable> listPicture = new ArrayList<>();
        ArrayList<String> listImgUrl = new ArrayList<>();
        Drawable addPicture = getResources().getDrawable(R.drawable.sjq_add_tupian_sel);
        listPicture.add(addPicture);
        final int childPosition = diseaseNewParentLayout.getChildCount();
        opinionGridAdapter = new OpinionGridAdapter(getContext(), this,  listPicture, listImgUrl, childPosition);
        sfzList.setAdapter(opinionGridAdapter);
        mapAdapter.put(childPosition, opinionGridAdapter);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_Male:
                isty = "true";
                break;
            case R.id.rb_FeMale:
                isty = "false";
                break;
            default:
                break;
        }
    }

    @Override
    public void addDatas(AddBean addBean) {
        ToastUtils.showShortToast(addBean.getMessage());
        Intent intent = new Intent();
        getActivity().setResult(2, intent);
        getActivity().finish();
    }

    private void getkdxf(final EditText kdaxfdate) {
        dictationResultStr = "[";
        // 语音配置对象初始化
        SpeechUtility.createUtility(getActivity(), SpeechConstant.APPID + "=" + APPID);
        // 1.创建SpeechRecognizer对象，第2个参数：本地听写时传InitListener
        SpeechRecognizer mIat = SpeechRecognizer.createRecognizer(getActivity(), null);
        // 交互动画
        final RecognizerDialog iatDialog = new RecognizerDialog(getActivity(), null);
        // 2.设置听写参数，详见《科大讯飞MSC API手册(Android)》SpeechConstant类
        mIat.setParameter(SpeechConstant.DOMAIN, "iat");
        mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        mIat.setParameter(SpeechConstant.ACCENT, "mandarin");
        // 3.开始听写
        iatDialog.setListener(new RecognizerDialogListener() {
            @Override
            public void onResult(RecognizerResult results, boolean isLast) {

                if (!isLast) {
                    dictationResultStr += results.getResultString() + ",";
                } else {
                    dictationResultStr += results.getResultString() + "]";
                }
                if (isLast) {
                    List<DictationResult> dictationResultList = JSON.parseArray(dictationResultStr, DictationResult.class);
                    String finalResult = "";
                    for (int i = 0; i < dictationResultList.size() - 1; i++) {
                        finalResult += dictationResultList.get(i)
                                .toString();
                    }
                    xf.clear();
                    zong.clear();
                    zong.add(kdaxfdate.getText().toString());
                    zong.add(finalResult);
                    kdaxfdate.setText(listToString2(zong));
                    kdaxfdate.requestFocus();
                    kdaxfdate.setSelection(listToString2(zong).length());
                }
            }

            @Override
            public void onError(SpeechError error) {
                error.getPlainDescription(true);
            }

        });
        iatDialog.show();

    }

    public static String listToString2(List<String> list) {
        StringBuilder sb = new StringBuilder();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (i < list.size() - 1) {
                    sb.append(list.get(i));
                } else {
                    sb.append(list.get(i));
                }
            }
        }
        return sb.toString();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 66 && resultCode == RESULT_OK) {
            final OpinionGridAdapter opinionGridAdapter = mapAdapter.get(childViewPosition);
            final ArrayList<Drawable> listPicture = opinionGridAdapter.getListPicture();
            final ArrayList<String> listImgUrl = opinionGridAdapter.getListImgUrl();
            String imgPath = Matisse.obtainCropResult(data);
            listPicture.remove(listPicture.size() - 1);
            Bitmap bitmap = Utils.getImageThumbnail(imgPath, Utils.dip2px(getContext(), 480),
                    Utils.dip2px(getContext(), 480));
            if (bitmap != null) {
                Drawable drawable = new BitmapDrawable(bitmap);
                listPicture.add(drawable);
                listImgUrl.add(imgPath);
                Drawable addPicture = getResources().getDrawable(R.drawable.sjq_add_tupian_sel);
                listPicture.add(addPicture);
                opinionGridAdapter.notifyDataSetChanged();
                PicDatas.add(Utils.bmpToBase64String(Matisse.obtainCropResult(data)));
            }
        }
    }
}
